package com.fescoservice.controller;

import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import com.fescoservice.config.PropertiesConfig;
import com.fescoservice.exception.FSException;
import com.fescoservice.model.Company;
import com.fescoservice.model.Operator;
import com.fescoservice.service.CompanyService;
import com.fescoservice.service.OperatorService;
import com.fescoservice.util.PasswordUtil;

@Controller
@RequestMapping("/action/Manage.htm")
public class ManageController{
	private static final Logger log = LogManager.getLogger(ManageController.class);
	
	@Autowired
	private OperatorService operatorService;
	@Autowired
	private CompanyService companyService;

	@RequestMapping(params="cmd=manage")
	public String getMenuHeader(ModelMap map, HttpServletRequest request){	
		return "common/manage";
	}
	
	@RequestMapping(params="cmd=header")
	public String getHeader(ModelMap map, HttpServletRequest request){		
		String lang =(String)request.getSession().getAttribute("userLanguage");
		if(null==lang || lang.equals("")){
			lang=(String)request.getLocale().getLanguage();
			request.getSession().setAttribute("userLanguage",lang);
		}
		log.debug("~~~~~~~~language~~~~~~~~"+lang);
		return "common/header";
	}
	
	@RequestMapping(params="cmd=setLanguage")
	public String setLanguage(ModelMap map, HttpServletRequest request){		
		String lang =(String)request.getParameter("language");
		if(null==lang || lang.equals("")) lang=(String)request.getLocale().getLanguage();
		request.getSession().setAttribute("userLanguage",lang);
		map.addAttribute("lnguageChanged","Y");
		return "common/header";
	}
	
	
	@RequestMapping(params="cmd=menu")
	public String getMenu(ModelMap map, HttpServletRequest request){	
		return "common/menu";
	}
	
	@RequestMapping(params = "cmd=operatorlist")
	public String listCategory(String page,ModelMap map, HttpServletRequest request) throws FSException{
		String type = (String)request.getParameter("type");
		
		int pageNumber = Integer.parseInt((null==page || "".equals(page))?"1":page);
		getListModel(map,type,pageNumber);
		map.addAttribute("operType",type);
		return "manage/operatorlist";
	}
	
	@RequestMapping(params = "cmd=addOperatorInit")
	public String addOperatorInit(ModelMap map,HttpServletRequest request) throws FSException{		
		Operator oper = new Operator();
		oper.setOperId("");
		oper.setOperName("");
		oper.setOperEmail("");
		oper.setOperTel("");
		oper.setOperBirth("");
		oper.setOperCompanyId(0);
		map.addAttribute("operator",oper);
		map.addAttribute("companyName","");
		return "manage/addoperator";
	}

	@RequestMapping(params = "cmd=saveOperator")
	public String saveOperator(Operator operator,String operPassword1, ModelMap map,	HttpServletRequest request) throws FSException {
		if("0".equals(operator.getOperType())){
			//operator.setOperCompanyId();
			operator.setCompany(null);
		}else{
			operator.setOperDeptId("");
		}
		Operator oper = operatorService.getOperator(operator.getOperId());
		String pw =null;
		if(null==oper || !oper.getOperBirth().equals(operator.getOperBirth())){		
			pw = operator.getOperBirth().substring(6,10)+operator.getOperBirth().substring(0,2)+operator.getOperBirth().substring(3,5);
			operator.setOperPassword(PasswordUtil.encryptPassword(operator.getOperId(),pw));
		}else if(null!=operPassword1 && !"".equals(operPassword1)){
			operator.setOperPassword(PasswordUtil.encryptPassword(operator.getOperId(),operPassword1));
		}else{
			operator.setOperPassword(oper.getOperPassword());
		}
		operatorService.saveOperator(operator);
		getListModel(map,null,1);
		return "manage/operatorlist";
	}
	
	@RequestMapping(params = "cmd=modifyOperatorInit")
	public String modifyOperatorInit(ModelMap map,HttpServletRequest request) throws FSException{
		String id = (String)request.getParameter("operId");
		Operator oper = operatorService.getOperator(id);
		String companyName ="";
		if(oper.getOperCompanyId()>0){
			companyName =companyService.findCompanyNameById(oper.getOperCompanyId());
		}
		map.addAttribute("operator",oper);
		map.addAttribute("companyName",companyName);
		return "manage/addoperator";
	}	
	
	@RequestMapping(params = "cmd=deleteOperator")
	public String deleteOperator(ModelMap map,HttpServletRequest request) throws FSException{
		String id = (String)request.getParameter("operId");
		operatorService.deleteOperator(id);
		getListModel(map,null,1);
		return "manage/operatorlist";
	}
	
	
	
	private ModelMap getListModel(ModelMap map, String type,int pageNumber) throws FSException{
		//String operType = "";
		if("all".equals(type)) type=null;
		Long counts  = operatorService.countOperators(type);
		int first = PropertiesConfig.getInstance().getInt("ListSize.Operator")*(pageNumber-1);
		List list = operatorService.listOperators(type,first);
		map.addAttribute("operatorlist", list);
		map.addAttribute("counts", counts);
		map.addAttribute("pageNumber", pageNumber);
		return map;
	}
	
	@RequestMapping(params = "cmd=visaservice")
	public String visaService(ModelMap map,HttpServletRequest request) throws FSException{
		
		getServiceListModel(map,null,1);
		return "manage/servicelist";
	}
	
	@RequestMapping(params = "cmd=exitservice")
	public String exitService(ModelMap map,HttpServletRequest request) throws FSException{
		
		getServiceListModel(map,null,1);
		return "manage/servicelist";
	}
	
	@RequestMapping(params = "cmd=driveservice")
	public String driveService(ModelMap map,HttpServletRequest request) throws FSException{
		
		getServiceListModel(map,null,1);
		return "manage/servicelist";
	}
	
	private ModelMap getServiceListModel(ModelMap map, String type,int pageNumber) throws FSException{
		//String operType = "";
		if("all".equals(type)) type=null;
		Long counts  = operatorService.countOperators(type);
		int first = PropertiesConfig.getInstance().getInt("ListSize.Operator")*(pageNumber-1);
		List list = operatorService.listOperators(type,first);
		map.addAttribute("operatorlist", list);
		map.addAttribute("counts", counts);
		map.addAttribute("pageNumber", pageNumber);
		return map;
	}
	
	
	@RequestMapping(params = "cmd=checkOperatorId")
	public String checkOperatorId(ModelMap map, String operId) throws FSException{	
		//Operator oper  = operatorService.getOperator(operId);	
		log.debug("~~~~~~~~~~~~~checkOperatorId~~~`"+operId+"~~~~~~~~~~~~~~~~~~~~~");
		String result="false";
		if(operatorService.checkOperIdExists(operId)>0){
			result="true";
		}
		map.addAttribute("result", result);
		return "common/ajaxresult";
	}
	
	@RequestMapping(params = "cmd=getCompaniesJson")
	public String getCompaniesJson(ModelMap map, String name_startsWith) throws FSException{	
		List list  = companyService.getAllCompanies(name_startsWith);		
		log.debug("~~~~~~~~~~~~~getCompaniesJson~~~`"+name_startsWith+"~~~~~~~~~~~~~~~~~~~~~");
		StringBuffer result=new StringBuffer("{\"totalResultsCount\":0,\"companyNames\":[{");
		Company comp = null;
		for(int i=0;i<list.size();i++){
			comp = (Company)list.get(i);
			if (i>0) result.append(",");
			result.append("\"label\": \"").append(comp.getCompName()).append("\",");
			result.append("\"value\": ").append(comp.getCompId()).append("}");
		}	
		result.append("]}");
		map.addAttribute("result", result.toString());
		return "common/ajaxresult";
	}
	
	@RequestMapping(params = "cmd=getCompanyList")
	public String getCompanyList(ModelMap map, String name) throws FSException{	
		System.out.println("L176============================================================name:"+name);
		
		String compName = "";
		try {
			 compName = new String(name.getBytes("ISO-8859-1"),"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		List list  = companyService.getAllCompanies(compName);		
		log.debug("~~~~~~~~~~~~~getCompanyList~~~`"+name+"~~~~~~~~~~~~~~~~~~~~~");
		
		map.addAttribute("companyList", list);
		return "common/choosecompany";
	}
	
}
